class WebSocketClient {
    constructor(url, pingInterval = 30000, reconnectInterval = 1000) {
        this.url = url; // WebSocket 地址
        this.pingInterval = pingInterval;
        this.reconnectInterval = reconnectInterval;
        this.ws = null;
        this.reconnectAttempts = 0;
        this.pingIntervalId = null;
    }

    // 初始化 WebSocket
    init() {
        this.ws = new WebSocket(this.url);

        // 监听 WebSocket 事件
        this.ws.onopen = this.onOpen.bind(this);
        this.ws.onmessage = this.onMessage.bind(this);
        this.ws.onclose = this.onClose.bind(this);
        this.ws.onerror = this.onError.bind(this);
    }

    // 连接成功时触发
    onOpen() {
        console.log("socket ok");
        this.reconnectAttempts = 0;
        this.startHeartbeat();
    }

    // 接收到消息时触发
    onMessage(event) {
        console.log("收到消息:", event.data);
        if (this.onReceiveMessage) {
            this.onReceiveMessage(event.data);
        }
    }

    // 连接关闭时触发
    onClose() {
        console.log("WebSocket 连接已关闭");
        this.stopHeartbeat();
        this.reconnect();
    }

    // 连接错误时触发
    onError(error) {
        console.error("WebSocket 错误:", error);
    }

    // 发送消息
    sendMessage(message) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            console.log("发送消息:", message);
            this.ws.send(message);
        } else {
            console.log("WebSocket 未连接");
        }
    }

    // 启动心跳机制
    startHeartbeat() {
        this.pingIntervalId = setInterval(() => {
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                console.log("发送心跳包");
                this.ws.send("ping");
            }
        }, this.pingInterval);
    }

    // 停止心跳机制
    stopHeartbeat() {
        if (this.pingIntervalId) {
            clearInterval(this.pingIntervalId);
        }
    }

    // 断线重连
    reconnect() {
        if (this.reconnectAttempts < 5) {
            this.reconnectAttempts++;
            console.log(`正在重连... 第${this.reconnectAttempts}次`);
            setTimeout(() => {
                this.init(); // 尝试重新连接
            }, this.reconnectInterval * this.reconnectAttempts);
        } else {
            console.log("重连失败，已超过最大重试次数");
        }
    }

    // 设置接收到消息时的回调
    setOnReceiveMessage(callback) {
        this.onReceiveMessage = callback;
    }

    // 关闭 WebSocket
    close() {
        if (this.ws) {
            this.ws.close();
        }
    }
}

export default WebSocketClient;
